﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Sales;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class GetStocksWithBOM : RibbonForm
    {
        public GetStocksWithBOM()
        {
            InitializeComponent();
        }

        public string PriceListCode { get; set; }
        public string ItemGuID { get; set; }
        public string DocumentNumber { get; set; }
        public string ItemCode { get; set; }
        public string ItemName { get; set; }
        public string UoM { get; set; }
        public string OrderQty { get; set; }
        public string WhsCode { get; set; }
        public string WhsName { get; set; }
        public string TotalServed { get; set; }
        public int PackSize { get { return 1; } }

        public string ConnectionString { get; set; }
        public DataTable DeliveredIssuedItems { get; set; }
        public DataTable BOMLineItems { get; set; }
        public DataTable StockCard { get; set; }
        #region Initialize

        public DataTable InitializeIssuedItems()
        {
            DataTable _table = new DataTable();

            _table.Columns.Add("ItemCode", typeof(string));
            _table.Columns.Add("ItemName", typeof(string));
            _table.Columns.Add("QtySrvd", typeof(string));
            _table.Columns.Add("UnitCost", typeof(string));
            _table.Columns.Add("UoM", typeof(string));
            _table.Columns.Add("IsFree", typeof(bool));
            _table.Columns.Add("LotNumber", typeof(string));
            _table.Columns.Add("PriceListCode", typeof(string));
            _table.Columns.Add("ItemGuID", typeof(string));

            return _table;
        }

        public DataTable InitStockCard()
        {
            DataTable _table = new DataTable();

            _table.Columns.Add("WhsCode", typeof(string));
            _table.Columns.Add("WhsName", typeof(string));
            _table.Columns.Add("ItemCode", typeof(string));
            _table.Columns.Add("ItemName", typeof(string));
            _table.Columns.Add("Qty", typeof(double));
            _table.Columns.Add("UnitCost", typeof(string));
            _table.Columns.Add("UoM", typeof(string));
            _table.Columns.Add("LotNumber", typeof(string));
            _table.Columns.Add("ExpiryDate", typeof(DateTime));
            

            return _table;

        }
        #endregion

        #region Functions
        bool IsNumeric(string _VAR_VALUE)
        {
            try
            {
                int _var = Convert.ToInt16(_VAR_VALUE);

                return true;
            }
            catch
            {
                return false;
            }
        }

        void BindBOM()
        {
            ItemManager oItemManager = new ItemManager();
            KitManager oManager = new KitManager();




            oItemManager.ConnectionString = this.ConnectionString;
            oItemManager.Open();
            string sItemBoM = oItemManager.GetDefaultBOM(txtItemcode.Text);
            oItemManager.Close();
            if (sItemBoM != null)
            {
                DataTable _table = new DataTable();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                double _ORDR =  Convert.ToDouble(this.OrderQty);
                _table = oManager.GetLineItems(sItemBoM, (int)_ORDR);
                oManager.Close();
                this.BOMLineItems = _table;

                gridControl3.DataSource = this.BOMLineItems;
                gridControl3.Refresh();
            }
        }
    
        void BindStock()
        {
            this.StockCard = InitStockCard();

            foreach (DataRow oRow in this.BOMLineItems.Rows)
            {
                

                #region Getting the stocks per Item Code in BoM
                StockManager oManager = new StockManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable _stockCardTable = oManager.GetAvailableStockByItemCode(this.WhsCode, oRow["ItemCode"].ToString());
                oManager.Close();
                #endregion

                foreach (DataRow _RowAvailStocks in _stockCardTable.Rows)
                {
                    DataRow oStockCardRow = this.StockCard.NewRow();

                    oStockCardRow["WhsCode"] = _RowAvailStocks["WhsCode"];
                    oStockCardRow["WhsName"] = _RowAvailStocks["WhsName"];
                    oStockCardRow["ItemCode"] = _RowAvailStocks["ItemCode"];
                    oStockCardRow["ItemName"] = _RowAvailStocks["ItemName"];
                    oStockCardRow["Qty"] = _RowAvailStocks["Qty"];
                    oStockCardRow["UoM"] = _RowAvailStocks["UoM"];
                    oStockCardRow["LotNumber"] = _RowAvailStocks["LotNumber"];
                    oStockCardRow["ExpiryDate"] = _RowAvailStocks["ExpiryDate"];
                    oStockCardRow["UnitCost"] = _RowAvailStocks["UnitCost"];

                    foreach (DataRow dRow   in this.DeliveredIssuedItems.Rows)
                    {
                        if (dRow.RowState != DataRowState.Deleted)
                        {
                            if (oStockCardRow["ItemCode"].ToString() == dRow["ItemCode"].ToString() && oStockCardRow["LotNumber"].ToString() == dRow["LotNumber"].ToString())
                            {
                                oStockCardRow["Qty"] = Convert.ToDouble(oStockCardRow["Qty"]) - Convert.ToDouble(dRow["QtySrvd"]);
                            }
                        }
                    }

                    this.StockCard.Rows.Add(oStockCardRow);
                }
                
            }


            gridControl1.DataSource = this.StockCard;
            gridControl1.Refresh();
        }
        #endregion

        #region Form Events

        private void btnCancel_Click(object sender, EventArgs e)
        {
            double _total = 0;
            bool HasRows;

            HasRows = false;
            if (this.DeliveredIssuedItems.Rows.Count > 0)
            {
               
                foreach (DataRow oRow in this.DeliveredIssuedItems.Rows)
                {
                    if (oRow.RowState != DataRowState.Deleted)
                    {
                        if (this.ItemGuID == oRow["ItemGuID"].ToString().Trim())
                        {
                            HasRows = true;
                        }
                    }
                }

            }
            if (HasRows == false)
            {
                _total = 0;
            }
            else
            {
                _total = Convert.ToDouble(txtQtyOrder.Text);
            }
            this.TotalServed = _total.ToString();
            this.Close();
        }


        private void GetStocksForDeliver_Load(object sender, EventArgs e)
        {
            txtWarehouse.Text = this.WhsName;
            txtItemcode.Text = this.ItemCode;
            txtDescription.Text = this.ItemName;
            txtUoM.Text = this.UoM;
            txtQtyOrder.Text = this.OrderQty;

            BindBOM();

            BindStock();

            gridControl2.DataSource = this.DeliveredIssuedItems;
            gridControl2.Refresh();

            gridView2.FindFilterText = this.ItemGuID;
            
        }

        private void txtPickItem_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

            if (oButtonEdit.Text != "" && IsNumeric(oButtonEdit.Text))
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];

                double _QtySrvd = Convert.ToDouble(oButtonEdit.Text);
                double _AvailableQty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]));

                if (_QtySrvd>_AvailableQty)
                {
                    MessageBox.Show("Please enter not less than to the available quantity!!!", "On-Hand", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    string _LOT_NUMBER = gridView1.GetRowCellValue(iCount, gridView1.Columns["LotNumber"]).ToString();

                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], _AvailableQty - _QtySrvd);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["PickQty"], 0);

                    DataRow oRowItem = this.DeliveredIssuedItems.NewRow();

                    oRowItem["ItemCode"] = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]);
                    oRowItem["ItemName"] = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemName"]);
                    oRowItem["UnitCost"] = gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitCost"]);
                    oRowItem["PriceListCode"] = this.PriceListCode;
                    oRowItem["QtySrvd"] = _QtySrvd;
                    oRowItem["UoM"] = txtUoM.Text;
                    oRowItem["LotNumber"] = _LOT_NUMBER;
                    oRowItem["ItemGuID"] = this.ItemGuID;


                    this.DeliveredIssuedItems.Rows.Add(oRowItem);
                    this.DeliveredIssuedItems.AcceptChanges();
                    gridControl2.DataSource = this.DeliveredIssuedItems;
                    gridControl2.Refresh();
                }
            }

            

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            double _total = 0;
            

            _total = Convert.ToDouble(txtQtyOrder.Text);

            this.TotalServed = _total.ToString();
            this.Close();
        }

        private void txtPickItem_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                if (oButtonEdit.Text != "" && IsNumeric(oButtonEdit.Text))
                {
                    int iCount = -1;
                    int[] oRow = gridView1.GetSelectedRows();

                    iCount = oRow[0];

                    double _QtySrvd = Convert.ToDouble(oButtonEdit.Text);
                    double _AvailableQty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]));
                    
                    string _LOT_NUMBER = gridView1.GetRowCellValue(iCount, gridView1.Columns["LotNumber"]).ToString();

                    if (_QtySrvd > _AvailableQty)
                    {
                        MessageBox.Show("Please enter not less than to the available quantity!!!", "On-Hand", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    else
                    {
                        gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], _AvailableQty - _QtySrvd);
                        gridView1.SetRowCellValue(iCount, gridView1.Columns["PickQty"], 0);

                        DataRow oRowItem = this.DeliveredIssuedItems.NewRow();

                        //oRowItem["ItemCode"] = txtItemcode.Text;
                        //oRowItem["ItemName"] = txtDescription.Text;
                        oRowItem["ItemCode"] = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]);
                        oRowItem["ItemName"] = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemName"]);
                        oRowItem["UnitCost"] = gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitCost"]);
                        oRowItem["PriceListCode"] = this.PriceListCode;
                        oRowItem["QtySrvd"] = _QtySrvd;
                        oRowItem["UoM"] = txtUoM.Text;
                        oRowItem["LotNumber"] = _LOT_NUMBER;
                        oRowItem["ItemGuID"] = this.ItemGuID;

                        this.DeliveredIssuedItems.Rows.Add(oRowItem);
                        this.DeliveredIssuedItems.AcceptChanges();

                        gridControl2.DataSource = this.DeliveredIssuedItems;
                        gridControl2.Refresh();
                    }
                }

            }
        }

        private void gridControl2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                int iCount = -1;
                int[] oRow = gridView2.GetSelectedRows();

                iCount = oRow[0];
            
                gridView2.DeleteRow(iCount);
                gridView2.RefreshData();

                
            }
        }
        #endregion

        private void txtQtyOrder_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        private void txtQtyOrder_Leave(object sender, EventArgs e)
        {
            try
            {
                double _OrderValue = Convert.ToDouble(txtQtyOrder.Text);
                this.OrderQty = txtQtyOrder.Text;
                BindBOM();

                this.DeliveredIssuedItems.Rows.Clear();

                gridControl2.DataSource = this.DeliveredIssuedItems;
                gridControl2.Refresh();

            }
            catch
            {
                this.OrderQty = txtQtyOrder.Text;
            }
        }

        private void btnPick_Click(object sender, EventArgs e)
        {
            foreach (DataRow oRow in this.BOMLineItems.Rows)
            {

                double _QtyRequirement = Convert.ToDouble(oRow["TotalRqmt"]);
                double _QtyRequired = Convert.ToDouble(oRow["TotalRqmt"]);
                double _QtyGathered = 0;

                foreach (DataRow oRowStocks in this.StockCard.Rows)
                {
                    if (oRow["ItemCode"].ToString() == oRowStocks["ItemCode"].ToString())
                    {

                        double _AvailableQty = Convert.ToDouble(oRowStocks["Qty"]);

                        string _LOT_NUMBER = oRowStocks["LotNumber"].ToString();

                        if (_QtyRequired > _AvailableQty)
                        {
                            _QtyGathered = _QtyGathered + _AvailableQty;
                            _QtyRequired = _QtyRequired - _AvailableQty;

                            oRowStocks["Qty"] = Convert.ToDouble(oRowStocks["Qty"]) -  _AvailableQty;

                            DataRow oRowItem = this.DeliveredIssuedItems.NewRow();

                            oRowItem["ItemCode"] = oRow["ItemCode"].ToString();
                            oRowItem["ItemName"] = oRow["ItemName"].ToString();
                            oRowItem["UnitCost"] = oRowStocks["UnitCost"].ToString();
                            oRowItem["PriceListCode"] = this.PriceListCode;
                            oRowItem["QtySrvd"] = _AvailableQty;
                            oRowItem["UoM"] = txtUoM.Text;
                            oRowItem["LotNumber"] = _LOT_NUMBER;
                            oRowItem["IsFree"] = (bool)oRow["IsFree"];
                            oRowItem["ItemGuID"] = this.ItemGuID;

                            this.DeliveredIssuedItems.Rows.Add(oRowItem);
                            this.DeliveredIssuedItems.AcceptChanges();

                        }
                        else
                        {
                           
                            _QtyGathered = _QtyGathered + _QtyRequired;
                           oRowStocks["Qty"] =  _AvailableQty - _QtyRequired;
                           
                            DataRow oRowItem = this.DeliveredIssuedItems.NewRow();

                            oRowItem["ItemCode"] = oRow["ItemCode"].ToString();
                            oRowItem["ItemName"] = oRow["ItemName"].ToString();
                            oRowItem["UnitCost"] = oRowStocks["UnitCost"].ToString();
                            oRowItem["PriceListCode"] = this.PriceListCode;
                            oRowItem["QtySrvd"] = _QtyRequired;
                            oRowItem["UoM"] = txtUoM.Text;
                            oRowItem["LotNumber"] = _LOT_NUMBER;
                            oRowItem["IsFree"] = (bool)oRow["IsFree"];
                            oRowItem["ItemGuID"] = this.ItemGuID;

                            this.DeliveredIssuedItems.Rows.Add(oRowItem);
                            this.DeliveredIssuedItems.AcceptChanges();

                            break;  
                        }

                      
                    }
                }


                if (_QtyGathered != _QtyRequirement)
                {

                    List<DataRow> lRows = new List<DataRow>();

                    foreach (DataRow row in this.DeliveredIssuedItems.Rows)
                    {
                        if (row["ItemGuID"].ToString() == this.ItemGuID)
                        {
                            lRows.Add(row);
                        }
                    }

                    foreach (DataRow row in lRows)
                    {
                        this.DeliveredIssuedItems.Rows.Remove(row);
                    }
                    this.DeliveredIssuedItems.AcceptChanges();

                    BindStock();
                    txtQtyOrder.Text = "0";
                    MessageBox.Show("Inventory is not sufficient!!!", "Inventory", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }

            
            gridControl2.DataSource = this.DeliveredIssuedItems;
            gridControl2.Refresh();
        }

        private void gridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                BindStock();
            }
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }
    }
}
